﻿using System;
using System.Collections.Generic;
using System.Text;
using Placid.Core;
using System.Data;

namespace Placid.PivotSourceImpl
{
    public class PivotSource : IPivotSource
    {
        internal protected DataTable _source;

        private PivotSourceColumnsCollection _columns;
        private PivotSourceRowsCollection _rows;

        public PivotSource(DataTable source)
        {
            if(source != null) {
                _source = source;
            } else throw new Exception("Source reference is null.");

            _columns = new PivotSourceColumnsCollection(this);
            _rows = new PivotSourceRowsCollection(this);
        }

        public PivotSourceColumnsCollection Columns
        {
            get { return _columns; }
        }

        public PivotSourceRowsCollection Rows
        {
            get { return _rows; }
        }

        #region IPvSource Members

        public IPivotSourceRow GetRow(int rowIndex)
        {
            if(_rows != null) return _rows[rowIndex];
            else return null;
        }

        public IPivotSourceColumn GetColumn(int columnIndex)
        {
            if(_columns != null) return _columns[columnIndex];
            else return null;
        }

        public IPivotSourceColumn GetColumn(string columnName)
        {
            if(_columns != null) return _columns[columnName];
            else return null;
        }

        public IPivotSourceCell GetCell(int rowIndex, int colIndex)
        {
            return _rows[rowIndex].Cells[colIndex];
        }

        public int RowsCount
        {
            get
            {
                if(_rows != null) return _rows.Count;
                else return 0;
            }
        }

        public int ColumnsCount
        {
            get
            {
                if(_columns != null) return _columns.Count;
                else return 0; ;
            }
        }

        #endregion

        public override string ToString()
        {
            return "Columns : " + ColumnsCount.ToString() + ", Rows: " + RowsCount.ToString();
        }


        #region IDisposable Members

        public void Dispose()
        {
            if(_source.Rows != null) _source.Dispose();
            _columns.Clear();
            _rows.Clear();
        }

        #endregion
    }
}
